/**
 * 专注模式管理器
 * 提供全屏专注界面，屏蔽干扰
 */

class FocusMode {
    constructor() {
        this.isActive = false;
        this.overlay = null;
        this.originalTitle = document.title;
        this.titleBlinkInterval = null;
        this.isBlinking = false;
        this.settings = this.loadSettings();
        
        // 干扰网站列表
        this.distractingDomains = [
            'facebook.com', 'twitter.com', 'instagram.com', 'youtube.com',
            'tiktok.com', 'weibo.com', 'zhihu.com', 'bilibili.com',
            'reddit.com', 'pinterest.com', 'linkedin.com', 'snapchat.com',
            'douyin.com', 'xiaohongshu.com', 'kuaishou.com'
        ];
        
        this.init();
    }
    
    /**
     * 初始化专注模式
     */
    init() {
        this.createOverlay();
        this.setupEventListeners();
        this.checkForDistractions();
    }
    
    /**
     * 创建专注模式覆盖层
     */
    createOverlay() {
        this.overlay = document.createElement('div');
        this.overlay.className = 'focus-mode-overlay';
        this.overlay.innerHTML = `
            <div class="focus-mode-content">
                <button class="focus-mode-exit" id="focusModeExit">×</button>
                <h1 class="focus-mode-title" id="focusModeTitle">专注工作</h1>
                <p class="focus-mode-subtitle">保持专注，远离干扰</p>
                <div class="focus-mode-timer" id="focusModeTimer">25:00</div>
                <div class="focus-mode-controls">
                    <button class="focus-mode-btn primary" id="focusModePause">⏸</button>
                    <button class="focus-mode-btn" id="focusModeMinimize">⤓</button>
                </div>
                <div class="focus-mode-tips">
                    <p>💡 提示：按 ESC 键可快速退出专注模式</p>
                    <p>🎯 保持专注，每次只处理一个任务</p>
                    <p>⏰ 时间到了会有提醒，不用担心错过</p>
                </div>
            </div>
        `;
        
        document.body.appendChild(this.overlay);
    }
    
    /**
     * 设置事件监听器
     */
    setupEventListeners() {
        // 退出按钮
        const exitBtn = document.getElementById('focusModeExit');
        if (exitBtn) {
            exitBtn.addEventListener('click', () => {
                this.exit();
            });
        }
        
        // 暂停按钮
        const pauseBtn = document.getElementById('focusModePause');
        if (pauseBtn) {
            pauseBtn.addEventListener('click', () => {
                this.togglePause();
            });
        }
        
        // 最小化按钮
        const minimizeBtn = document.getElementById('focusModeMinimize');
        if (minimizeBtn) {
            minimizeBtn.addEventListener('click', () => {
                this.minimize();
            });
        }
        
        // ESC键退出
        document.addEventListener('keydown', (event) => {
            if (this.isActive && event.key === 'Escape') {
                this.exit();
            }
        });
        
        // 页面可见性变化
        document.addEventListener('visibilitychange', () => {
            if (this.isActive && document.hidden) {
                this.handlePageHidden();
            } else if (this.isActive && !document.hidden) {
                this.handlePageVisible();
            }
        });
    }
    
    /**
     * 进入专注模式
     */
    enter(timer) {
        if (this.isActive) return;
        
        this.isActive = true;
        this.timer = timer;
        this.overlay.classList.add('active');
        
        // 更新专注模式显示
        this.updateFocusMode();
        
        // 开始标题闪烁
        if (this.settings.titleBlink) {
            this.startTitleBlink();
        }
        
        // 显示干扰提醒
        if (this.settings.distractionAlert) {
            this.showDistractionAlert();
        }
        
        // 5秒后隐藏鼠标
        setTimeout(() => {
            if (this.isActive) {
                document.body.style.cursor = 'none';
            }
        }, 5000);
        
        console.log('Focus mode entered');
    }
    
    /**
     * 退出专注模式
     */
    exit() {
        if (!this.isActive) return;
        
        this.isActive = false;
        this.overlay.classList.remove('active');
        
        // 恢复鼠标
        document.body.style.cursor = 'default';
        
        // 停止标题闪烁
        this.stopTitleBlink();
        
        // 恢复原始标题
        document.title = this.originalTitle;
        
        console.log('Focus mode exited');
    }
    
    /**
     * 切换暂停/继续
     */
    togglePause() {
        if (this.timer) {
            if (this.timer.isRunning) {
                this.timer.pause();
            } else {
                this.timer.start();
            }
        }
    }
    
    /**
     * 最小化专注模式
     */
    minimize() {
        this.overlay.classList.remove('active');
    }
    
    /**
     * 更新专注模式显示
     */
    updateFocusMode() {
        if (!this.isActive || !this.timer) return;
        
        const status = this.timer.getStatus();
        
        // 更新标题
        const titleElement = document.getElementById('focusModeTitle');
        if (titleElement) {
            const titles = {
                work: '专注工作',
                short_break: '短暂休息',
                long_break: '长时休息'
            };
            titleElement.textContent = titles[status.state] || '专注模式';
        }
        
        // 更新副标题
        const subtitleElement = document.getElementById('focusModeSubtitle');
        if (subtitleElement) {
            const subtitles = {
                work: '保持专注，远离干扰',
                short_break: '放松一下，准备下一轮',
                long_break: '充分休息，恢复精力'
            };
            subtitleElement.textContent = subtitles[status.state] || '保持专注';
        }
        
        // 更新时间显示
        const timerElement = document.getElementById('focusModeTimer');
        if (timerElement) {
            timerElement.textContent = status.formattedTime;
        }
        
        // 更新暂停按钮
        const pauseBtn = document.getElementById('focusModePause');
        if (pauseBtn) {
            pauseBtn.textContent = status.isRunning ? '⏸' : '▶';
        }
    }
    
    /**
     * 开始标题闪烁
     */
    startTitleBlink() {
        if (this.titleBlinkInterval) return;
        
        this.isBlinking = true;
        let blinkState = false;
        
        this.titleBlinkInterval = setInterval(() => {
            if (!this.isActive) {
                this.stopTitleBlink();
                return;
            }
            
            if (this.timer) {
                const status = this.timer.getStatus();
                const timeLeft = status.formattedTime;
                
                if (blinkState) {
                    document.title = `⏰ ${timeLeft} - 番茄时钟`;
                } else {
                    document.title = `专注中 - 番茄时钟`;
                }
                
                blinkState = !blinkState;
            }
        }, 2000);
    }
    
    /**
     * 停止标题闪烁
     */
    stopTitleBlink() {
        if (this.titleBlinkInterval) {
            clearInterval(this.titleBlinkInterval);
            this.titleBlinkInterval = null;
        }
        this.isBlinking = false;
    }
    
    /**
     * 检查干扰网站
     */
    checkForDistractions() {
        const currentDomain = window.location.hostname;
        
        const isDistractingSite = this.distractingDomains.some(domain => 
            currentDomain.includes(domain)
        );
        
        if (isDistractingSite && this.settings.distractionAlert) {
            this.showDistractionWarning();
        }
    }
    
    /**
     * 显示干扰网站警告
     */
    showDistractionWarning() {
        const warning = document.createElement('div');
        warning.className = 'distraction-warning';
        warning.innerHTML = `
            <div class="warning-content">
                <div class="warning-icon">⚠️</div>
                <h3>干扰网站警告</h3>
                <p>您正在访问一个可能干扰专注的网站。建议关闭此标签页，保持专注。</p>
                <div class="warning-actions">
                    <button class="warning-btn primary" onclick="window.close()">关闭网站</button>
                    <button class="warning-btn" onclick="this.parentElement.parentElement.parentElement.remove()">继续访问</button>
                </div>
            </div>
        `;
        
        warning.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 10000;
        `;
        
        document.body.appendChild(warning);
        
        // 5秒后自动关闭
        setTimeout(() => {
            if (warning.parentNode) {
                warning.remove();
            }
        }, 5000);
    }
    
    /**
     * 显示干扰提醒
     */
    showDistractionAlert() {
        if (this.isActive) {
            const alert = document.createElement('div');
            alert.className = 'focus-distraction-alert';
            alert.innerHTML = `
                <div class="alert-content">
                    <div class="alert-icon">⚡</div>
                    <p>专注模式已激活，请保持专注！</p>
                    <button class="alert-close" onclick="this.parentElement.parentElement.remove()">×</button>
                </div>
            `;
            
            alert.style.cssText = `
                position: fixed;
                top: 20px;
                left: 50%;
                transform: translateX(-50%);
                background: rgba(255, 107, 107, 0.9);
                color: white;
                padding: 16px 24px;
                border-radius: 8px;
                z-index: 10001;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
            `;
            
            document.body.appendChild(alert);
            
            // 3秒后自动关闭
            setTimeout(() => {
                if (alert.parentNode) {
                    alert.remove();
                }
            }, 3000);
        }
    }
    
    /**
     * 处理页面隐藏
     */
    handlePageHidden() {
        if (this.settings.titleBlink) {
            this.startTitleBlink();
        }
    }
    
    /**
     * 处理页面可见
     */
    handlePageVisible() {
        // 更新专注模式显示
        this.updateFocusMode();
    }
    
    /**
     * 加载设置
     */
    loadSettings() {
        try {
            const saved = localStorage.getItem('pomodoro_focus_mode_settings');
            if (saved) {
                return { ...this.getDefaultSettings(), ...JSON.parse(saved) };
            }
        } catch (error) {
            console.error('Error loading focus mode settings:', error);
        }
        
        return this.getDefaultSettings();
    }
    
    /**
     * 获取默认设置
     */
    getDefaultSettings() {
        return {
            enabled: true,
            titleBlink: true,
            distractionAlert: true,
            autoEnter: false,
            fullscreen: false
        };
    }
    
    /**
     * 保存设置
     */
    saveSettings(settings) {
        try {
            this.settings = { ...this.settings, ...settings };
            localStorage.setItem('pomodoro_focus_mode_settings', JSON.stringify(this.settings));
        } catch (error) {
            console.error('Error saving focus mode settings:', error);
        }
    }
    
    /**
     * 更新设置
     */
    updateSettings(newSettings) {
        this.saveSettings(newSettings);
    }
    
    /**
     * 获取设置
     */
    getSettings() {
        return { ...this.settings };
    }
    
    /**
     * 检查是否在专注模式
     */
    isInFocusMode() {
        return this.isActive;
    }
    
    /**
     * 销毁专注模式
     */
    destroy() {
        this.exit();
        if (this.overlay && this.overlay.parentNode) {
            this.overlay.parentNode.removeChild(this.overlay);
        }
    }
}

// 导出到全局作用域
window.FocusMode = FocusMode;